package com.ruoyi.ai.utils;

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.ChatCompletion;
import com.openai.models.ChatCompletionCreateParams;
import com.openai.models.ChatCompletionMessage;
import org.springframework.stereotype.Component;

@Component
public class AiUtil {

    private final String tyQwId="";
    private final   String baseUrl ="https://dashscope.aliyuncs.com/compatible-mode/v1";
    private final  String tyQwKey= "sk-759ff456ec9b4bb788061c7afc377d1f";

    public String sendMessage(String question){
        String answer = null;
        OpenAIClient client = OpenAIOkHttpClient.builder()
                .apiKey(tyQwKey)
                .baseUrl(baseUrl)
                .build();

        ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
                .addUserMessage(question)
                .model("qwen-plus")
                .build();

        try {
            ChatCompletion chatCompletion = client.chat().completions().create(params);
            // 提取回答内容（核心逻辑）
            // 判断 choices 列表是否为空
            if (chatCompletion.choices() != null && !chatCompletion.choices().isEmpty()) {
                // 取第一个回答（通常只有一个）
                ChatCompletion.Choice firstChoice = chatCompletion.choices().get(0);
                // 获取消息对象
                ChatCompletionMessage message = firstChoice.message();
                // 提取 content（即回答内容）
                if (message != null) {
                    answer = message.content().toString().replace("Optional[", "");
                    //去掉末尾的]
                    answer = answer.substring(0, answer.length() - 1);
                }
            }
        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
            e.printStackTrace();
        }
        return answer;
    }
}
